<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>文件管理 - Cloud DMS</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/layui-src/dist/css/layui.css">
    <script src="https://cdn.jsdelivr.net/npm/layui-src/dist/layui.js"></script>
    <style>
        .file-manager {
            padding: 20px;
        }
        .toolbar {
            margin-bottom: 20px;
        }
        .file-list {
            background: white;
            border-radius: 5px;
            overflow: hidden;
        }
        .file-item {
            padding: 15px;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .file-item:hover {
            background-color: #f8f8f8;
        }
        .file-info {
            display: flex;
            align-items: center;
            flex: 1;
        }
        .file-icon {
            margin-right: 10px;
            font-size: 20px;
            color: #4A90E2;
        }
        .file-details h4 {
            margin: 0;
            font-size: 14px;
            color: #333;
        }
        .file-details p {
            margin: 2px 0 0 0;
            font-size: 12px;
            color: #999;
        }
        .file-actions {
            display: flex;
            gap: 10px;
        }
        .upload-area {
            border: 2px dashed #d2d6de;
            border-radius: 5px;
            padding: 40px;
            text-align: center;
            margin-bottom: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .upload-area:hover {
            border-color: #4A90E2;
            background-color: #f8f9fa;
        }
        .upload-area.dragover {
            border-color: #4A90E2;
            background-color: #e7f1ff;
        }
    </style>
</head>
<body>
    <div class="file-manager">
        <div class="layui-card">
            <div class="layui-card-header">
                <h2>我的文件</h2>
                <div style="float: right;">
                    <span>用户: <span id="username"></span></span>
                    <button class="layui-btn layui-btn-sm" onclick="logout()">退出</button>
                </div>
            </div>
            <div class="layui-card-body">
                <!-- 上传区域 -->
                <div class="upload-area" id="uploadArea">
                    <i class="layui-icon layui-icon-upload" style="font-size: 48px; color: #d2d6de;"></i>
                    <p>点击或拖拽文件到此处上传</p>
                    <input type="file" id="fileInput" style="display: none;" multiple>
                </div>
                
                <!-- 工具栏 -->
                <div class="toolbar">
                    <button class="layui-btn layui-btn-sm" onclick="refreshFileList()">
                        <i class="layui-icon layui-icon-refresh"></i> 刷新
                    </button>
                    <button class="layui-btn layui-btn-sm layui-btn-normal" onclick="showUploadDialog()">
                        <i class="layui-icon layui-icon-upload"></i> 上传文件
                    </button>
                    <div class="layui-inline" style="margin-left: 20px;">
                        <input type="text" id="searchInput" placeholder="搜索文件..." class="layui-input" style="width: 200px;">
                    </div>
                    <button class="layui-btn layui-btn-sm" onclick="searchFiles()">
                        <i class="layui-icon layui-icon-search"></i> 搜索
                    </button>
                </div>
                
                <!-- 存储统计 -->
                <div class="layui-row layui-col-space10" style="margin-bottom: 20px;">
                    <div class="layui-col-md3">
                        <div class="layui-card">
                            <div class="layui-card-body" style="text-align: center;">
                                <h3 id="totalFiles">0</h3>
                                <p>文件总数</p>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-card">
                            <div class="layui-card-body" style="text-align: center;">
                                <h3 id="totalSize">0 B</h3>
                                <p>总大小</p>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-card">
                            <div class="layui-card-body" style="text-align: center;">
                                <h3 id="activeSize">0 B</h3>
                                <p>有效大小</p>
                            </div>
                        </div>
                    </div>
                    <div class="layui-col-md3">
                        <div class="layui-card">
                            <div class="layui-card-body" style="text-align: center;">
                                <h3 id="deletedSize">0 B</h3>
                                <p>回收站</p>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 文件列表 -->
                <div class="file-list" id="fileList">
                    <div style="text-align: center; padding: 40px; color: #999;">
                        <i class="layui-icon layui-icon-loading layui-anim layui-anim-rotate layui-anim-loop" style="font-size: 24px;"></i>
                        <p>加载中...</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        layui.use(['layer', 'upload'], function() {
            var layer = layui.layer;
            var upload = layui.upload;
            
            // 初始化
            init();
            
            function init() {
                // 检查登录状态
                checkAuth();
                
                // 加载文件列表
                loadFileList();
                
                // 加载存储统计
                loadStorageStats();
                
                // 绑定上传事件
                bindUploadEvents();
            }
            
            // 检查认证状态
            function checkAuth() {
                var token = localStorage.getItem('token');
                var username = localStorage.getItem('username');
                
                if (!token) {
                    layer.msg('请先登录', {icon: 2}, function() {
                        window.location.href = '/auth/user-login';
                    });
                    return;
                }
                
                document.getElementById('username').textContent = username || '未知用户';
            }
            
            // 加载文件列表
            function loadFileList() {
                var token = localStorage.getItem('token');
                
                fetch('/api/files/list', {
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                })
                .then(response => response.json())
                .then(result => {
                    if (result.success) {
                        renderFileList(result.data);
                    } else {
                        document.getElementById('fileList').innerHTML = 
                            '<div style="text-align: center; padding: 40px; color: #999;">加载文件列表失败</div>';
                    }
                })
                .catch(error => {
                    console.error('加载文件列表失败:', error);
                    document.getElementById('fileList').innerHTML = 
                        '<div style="text-align: center; padding: 40px; color: #999;">网络错误</div>';
                });
            }
            
            // 渲染文件列表
            function renderFileList(files) {
                var fileListHtml = '';
                
                if (files.length === 0) {
                    fileListHtml = '<div style="text-align: center; padding: 40px; color: #999;">暂无文件</div>';
                } else {
                    files.forEach(function(file) {
                        var iconClass = getFileIcon(file.originalFilename);
                        var statusBadge = file.isDeleted ? '<span class="layui-badge layui-bg-gray">已删除</span>' : 
                                         file.isEncrypted ? '<span class="layui-badge layui-bg-blue">已加密</span>' : '';
                        
                        fileListHtml += `
                            <div class="file-item">
                                <div class="file-info">
                                    <i class="layui-icon ${iconClass} file-icon"></i>
                                    <div class="file-details">
                                        <h4>${file.originalFilename} ${statusBadge}</h4>
                                        <p>${file.fileSizeFormatted} • ${formatDate(file.createdAt)}</p>
                                        ${file.userTags ? '<p>标签: ' + file.userTags + '</p>' : ''}
                                    </div>
                                </div>
                                <div class="file-actions">
                                    ${!file.isDeleted ? 
                                        `<button class="layui-btn layui-btn-xs" onclick="downloadFile(${file.fileId})">下载</button>
                                         <button class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteFile(${file.fileId})">删除</button>` :
                                        `<button class="layui-btn layui-btn-xs layui-btn-warm" onclick="restoreFile(${file.fileId})">恢复</button>`
                                    }
                                </div>
                            </div>
                        `;
                    });
                }
                
                document.getElementById('fileList').innerHTML = fileListHtml;
            }
            
            // 加载存储统计
            function loadStorageStats() {
                var token = localStorage.getItem('token');
                
                fetch('/api/files/stats', {
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                })
                .then(response => response.json())
                .then(result => {
                    if (result.success) {
                        var stats = result.data;
                        document.getElementById('totalFiles').textContent = stats.totalFiles;
                        document.getElementById('totalSize').textContent = stats.totalSizeFormatted;
                        document.getElementById('activeSize').textContent = stats.activeSizeFormatted;
                        document.getElementById('deletedSize').textContent = stats.deletedSizeFormatted;
                    }
                })
                .catch(error => {
                    console.error('加载存储统计失败:', error);
                });
            }
            
            // 绑定上传事件
            function bindUploadEvents() {
                var uploadArea = document.getElementById('uploadArea');
                var fileInput = document.getElementById('fileInput');
                
                // 点击上传
                uploadArea.addEventListener('click', function() {
                    fileInput.click();
                });
                
                // 文件选择
                fileInput.addEventListener('change', function(e) {
                    if (e.target.files.length > 0) {
                        uploadFiles(e.target.files);
                    }
                });
                
                // 拖拽上传
                uploadArea.addEventListener('dragover', function(e) {
                    e.preventDefault();
                    uploadArea.classList.add('dragover');
                });
                
                uploadArea.addEventListener('dragleave', function(e) {
                    e.preventDefault();
                    uploadArea.classList.remove('dragover');
                });
                
                uploadArea.addEventListener('drop', function(e) {
                    e.preventDefault();
                    uploadArea.classList.remove('dragover');
                    if (e.dataTransfer.files.length > 0) {
                        uploadFiles(e.dataTransfer.files);
                    }
                });
            }
            
            // 上传文件
            function uploadFiles(files) {
                var token = localStorage.getItem('token');
                
                Array.from(files).forEach(function(file) {
                    var formData = new FormData();
                    formData.append('file', file);
                    
                    var loadIndex = layer.load(1, {
                        content: '上传中: ' + file.name
                    });
                    
                    fetch('/api/files/upload', {
                        method: 'POST',
                        headers: {
                            'Authorization': 'Bearer ' + token
                        },
                        body: formData
                    })
                    .then(response => response.json())
                    .then(result => {
                        layer.close(loadIndex);
                        
                        if (result.success) {
                            layer.msg('上传成功: ' + file.name, {icon: 1});
                            loadFileList(); // 刷新文件列表
                            loadStorageStats(); // 刷新统计
                        } else {
                            layer.msg('上传失败: ' + result.message, {icon: 2});
                        }
                    })
                    .catch(error => {
                        layer.close(loadIndex);
                        console.error('上传失败:', error);
                        layer.msg('上传失败: ' + file.name, {icon: 2});
                    });
                });
            }
            
            // 获取文件图标
            function getFileIcon(filename) {
                var ext = filename.split('.').pop().toLowerCase();
                var iconMap = {
                    'pdf': 'layui-icon-file',
                    'doc': 'layui-icon-file',
                    'docx': 'layui-icon-file',
                    'txt': 'layui-icon-file',
                    'jpg': 'layui-icon-picture',
                    'jpeg': 'layui-icon-picture',
                    'png': 'layui-icon-picture',
                    'gif': 'layui-icon-picture',
                    'mp4': 'layui-icon-video',
                    'avi': 'layui-icon-video',
                    'mp3': 'layui-icon-music',
                    'wav': 'layui-icon-music',
                    'zip': 'layui-icon-file',
                    'rar': 'layui-icon-file'
                };
                return iconMap[ext] || 'layui-icon-file';
            }
            
            // 格式化日期
            function formatDate(dateStr) {
                var date = new Date(dateStr);
                return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
            }
            
            // 全局函数
            window.refreshFileList = function() {
                loadFileList();
                loadStorageStats();
            };
            
            window.downloadFile = function(fileId) {
                var token = localStorage.getItem('token');
                window.open('/api/files/download/' + fileId + '?token=' + encodeURIComponent(token));
            };
            
            window.deleteFile = function(fileId) {
                layer.confirm('确定要删除这个文件吗？', {icon: 3, title: '确认删除'}, function(index) {
                    var token = localStorage.getItem('token');
                    
                    fetch('/api/files/' + fileId, {
                        method: 'DELETE',
                        headers: {
                            'Authorization': 'Bearer ' + token
                        }
                    })
                    .then(response => response.json())
                    .then(result => {
                        if (result.success) {
                            layer.msg('删除成功', {icon: 1});
                            loadFileList();
                            loadStorageStats();
                        } else {
                            layer.msg('删除失败: ' + result.message, {icon: 2});
                        }
                    })
                    .catch(error => {
                        console.error('删除失败:', error);
                        layer.msg('删除失败', {icon: 2});
                    });
                    
                    layer.close(index);
                });
            };
            
            window.restoreFile = function(fileId) {
                var token = localStorage.getItem('token');
                
                fetch('/api/files/' + fileId + '/restore', {
                    method: 'POST',
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                })
                .then(response => response.json())
                .then(result => {
                    if (result.success) {
                        layer.msg('恢复成功', {icon: 1});
                        loadFileList();
                        loadStorageStats();
                    } else {
                        layer.msg('恢复失败: ' + result.message, {icon: 2});
                    }
                })
                .catch(error => {
                    console.error('恢复失败:', error);
                    layer.msg('恢复失败', {icon: 2});
                });
            };
            
            window.searchFiles = function() {
                var searchTerm = document.getElementById('searchInput').value.trim();
                if (!searchTerm) {
                    layer.msg('请输入搜索关键词', {icon: 0});
                    return;
                }
                
                var token = localStorage.getItem('token');
                
                fetch('/api/files/search?tag=' + encodeURIComponent(searchTerm), {
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                })
                .then(response => response.json())
                .then(result => {
                    if (result.success) {
                        renderFileList(result.data);
                        layer.msg('找到 ' + result.total + ' 个文件', {icon: 1});
                    } else {
                        layer.msg('搜索失败', {icon: 2});
                    }
                })
                .catch(error => {
                    console.error('搜索失败:', error);
                    layer.msg('搜索失败', {icon: 2});
                });
            };
            
            window.logout = function() {
                layer.confirm('确定要退出登录吗？', {icon: 3, title: '确认退出'}, function(index) {
                    localStorage.clear();
                    layer.msg('已退出登录', {icon: 1}, function() {
                        window.location.href = '/auth/user-login';
                    });
                    layer.close(index);
                });
            };
        });
    </script>
</body>
</html>